#!/bin/bash
#
# openvswitch-nova
#
# chkconfig: 2345 23 89
# description: Apply initial OVS flows for Nova

# Copyright 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack Foundation
# Copyright (C) 2009, 2010, 2011 Nicira Networks, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

# source function library
if [ -f /etc/init.d/functions ]; then
    . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ]; then
    . /etc/rc.d/init.d/functions
elif [ -f /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
else
    echo "$0: missing LSB shell function library" >&2
    exit 1
fi

OVS_CONFIGURE_BASE_FLOWS=/etc/xensource/scripts/ovs_configure_base_flows.py

if test -e /etc/sysconfig/openvswitch-nova; then
    . /etc/sysconfig/openvswitch-nova
else
    echo "$0: missing configuration file: /etc/sysconfig/openvswitch-nova"
    exit 1
fi

if test -e /etc/xensource/network.conf; then
    NETWORK_MODE=$(cat /etc/xensource/network.conf)
fi

case ${NETWORK_MODE:=openvswitch} in
    vswitch|openvswitch)
        ;;
    bridge)
        exit 0
        ;;
    *)
        echo "Open vSwitch disabled (/etc/xensource/network.conf is invalid)" >&2
        exit 0
        ;;
esac

function run_ovs_conf_base_flows {
    local action="$1"
    local all_interfaces=$(cd /sys/class/net/; /bin/ls -d eth*)
    local interfaces="${INTERFACES-$all_interfaces}"
    for interface in $interfaces; do
	/usr/bin/python $OVS_CONFIGURE_BASE_FLOWS $action $interface
    done
}

function start {
    run_ovs_conf_base_flows online
}

function stop {
    run_ovs_conf_base_flows offline
}

function restart {
    run_ovs_conf_base_flows reset
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
        echo "usage: openvswitch-nova [start|stop|restart]"
        exit 1
        ;;
esac
